package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.in.SwMessageDTO;
import com.zdkj.subway.stm.entity.SwStReportErrorAlterApply;
import com.zdkj.subway.stm.entity.SwStStock;
import com.zdkj.subway.stm.entity.SwStTicketCheck;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.fegin.SupportService;
import com.zdkj.subway.stm.mapper.SwStReportErrorAlterAppayMapper;
import com.zdkj.subway.stm.mapper.SwStTicketCheckMapper;
import com.zdkj.subway.stm.service.SwStStockService;
import com.zdkj.subway.stm.service.SwStTicketCheckService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import com.zdkj.subway.stm.util.DateUtilStm;
import com.zdkj.subway.stm.util.JdbcUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;


/**
 * 车站车票库存日报表
 *
 * @author songtuo
 * @date 2020-07-14 11:52:58
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swststock")
@Api(value = "swststock", tags = "车站车票库存日报表")
@Slf4j
public class SwStStockController {

    /**
     * 已通知
     */
    private static final String CONFIRM_STATUS_YES = "1";
    private final SwStStockService swStStockService;
    private final SupportService supportService;

    private final SwStTicketCheckService swStTicketCheckService;
    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;
    @Resource
    SwStTicketCheckMapper swStTicketCheckMapper;
    @Resource
    SwStReportErrorAlterAppayMapper swStReportErrorAlterAppayMapper;
    private static final Logger LOGGER = LoggerFactory.getLogger(SwStStock.class);
    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param swStStock
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStStockPage(Page page, SwStStock swStStock) {
        if(swStStock.getConfirmStatus()==null || "".equals(swStStock.getConfirmStatus())){
            swStStock.setConfirmStatus(null);
        }
		
		//log.info("库存日报表查询 1111   票种===="+swStStock.getTicketTypeEn()+"----车票------"+swStStock.getTicketTypeParamEn());
        SwStStock swStStockAddObj = ObjectUtils.getDefaultObj(SwStStock.class);
        swStStock.setLineCode(swStStockAddObj.getLineCode());
        swStStock.setStationCode(swStStockAddObj.getStationCode());
        /*
		if("".equals(swStStock.getTicketTypeEn()) || "null".equals(swStStock.getTicketTypeEn())){
			swStStock.setTicketTypeEn(null);
        }
		if("".equals(swStStock.getTicketTypeParamEn())|| "null".equals(swStStock.getTicketTypeParamEn())){
			swStStock.setTicketTypeParamEn(null);
        }*/
		//log.info("库存日报表查询   票种===="+swStStock.getTicketTypeEn()+"----车票------"+swStStock.getTicketTypeParamEn());
        QueryWrapper<SwStStock> queryWrapper = Wrappers.query(swStStock);
        queryWrapper.orderByAsc("-STATISTICS_DATE", "TICKET_TYPE_EN","TICKET_TYPE_PARAM_EN");
        return R.ok(swStStockService.page(page, queryWrapper));
    }
    /**
     * 分页查询
     *
     * @param page      分页对象线网日报表审核查询
     * @param swStStock
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/pageSt")
    public R getSwStmStockPage(Page page, SwStStock swStStock) {
        /*SwStStock swStStockAddObj = ObjectUtils.getDefaultObj(SwStStock.class);
        swStStock.setLineCode(swStStockAddObj.getLineCode());
        swStStock.setStationCode(swStStockAddObj.getStationCode());*/
        QueryWrapper<SwStStock> queryWrapper = Wrappers.query(swStStock);
        queryWrapper.ne("CONFIRM_STATUS","0");
        queryWrapper.orderByAsc("-STATISTICS_DATE", "TICKET_TYPE_EN","TICKET_TYPE_PARAM_EN");
        return R.ok(swStStockService.page(page, queryWrapper));
    }

    /**
     * 通过id查询
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStStockService.getById(id));
    }


    @ApiOperation(value = "批量修改提交状态", notes = "批量修改提交状态")
    @PostMapping("/updateSwStStock")
    @Transactional
    public R inform(@RequestBody List<Integer> listIds,String checkDate) {
        //LocalDate beginDateTime = LocalDate.parse(checkDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //LocalDate generateTime = LocalDate.now();
        PigxUser user = SecurityUtils.getUser();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        List<SwStStock> list = new ArrayList<>();
        String checkDay = swStStockService.getCheckDay();
        try{
            //Date beginDateTime = sf.parse(checkDate);//xxxx-xx-25
            for(Integer id : listIds){
                SwStStock olddata = swStStockService.getById(id);
                SwStStock swStStock = new SwStStock();
                swStStock.setId(id);
                swStStock.setConfirmStatus("1");
                swStStock.setReportModifyStatus("0");//报表修改提交状态
                swStStock.setConformPersonId(user.getId());
                swStStock.setConfirmPersonJobNo(user.getUserCode());
                swStStock.setConformPersonName(user.getNikeName());
                //如果提交 当月25号  库存日报表的日期只有当月25号的数据会被重新赋值 其他都不会重新赋值
                //if(beginDateTime.equals(olddata.getStatisticsDate())&&"PTDCP".equals(olddata.getTicketTypeParamEn())){
                //    String linecode = user.getLineCode();
                //    String stationCode = user.getStationCode();
                //    swStStock.setScDcpAmount(olddata.getBalanceToday());
                //    SwStTicketCheck swStTicketChecks = swStTicketCheckMapper.getSwStTicketCheck(checkDate,linecode,stationCode);
                //    if(swStTicketChecks != null){
                //        swStStock.setBalanceToday(swStTicketChecks.getRealCheckNumber());
                //    }
                //}
                Date statisticsDate = olddata.getStatisticsDate();
                String toString = DateUtilStm.dateToString(statisticsDate,"yyyy-MM-dd");
                //盘点日期从字典获取
                String newDate = toString.substring(0, 8) + checkDay;
                Date newDateTime = sf.parse(newDate);

                //如果提交 不论是不是当月的，都按照实际盘点时间 获取25号 进行对比  库存日报表的日期只有25号的数据会被重新赋值 其他都不会重新赋值
                if(newDateTime.equals(olddata.getStatisticsDate())&&"PTDCP".equals(olddata.getTicketTypeParamEn())){
                    String linecode = user.getLineCode();
                    String stationCode = user.getStationCode();
                    //swStStock.setScDcpAmount(olddata.getBalanceToday());
                    //SC对应的本日结存=上日结存+调入本站+配入本站+AGM回收+人工回收-票房售出-车票替换-TVM售出-网络售出-调出本站-上交车票
                    swStStock.setScDcpAmount(olddata.getBalanceLastday() + olddata.getTransferStation() + olddata.getDistributionStation() + olddata.getAgmRecovery() + olddata.getArtificialRecovery()
                            - olddata.getBoxOfficeSale() - olddata.getTicketReplace() - olddata.getTvmSellOut() - olddata.getInternetSales() - olddata.getLeaveStation() - olddata.getHandTicket());
                    SwStTicketCheck swStTicketChecks = swStTicketCheckMapper.getSwStTicketCheck(newDate,linecode,stationCode);
                    if(swStTicketChecks != null){
                        swStStock.setBalanceToday(swStTicketChecks.getRealCheckNumber());
                    }
                }
                if("1".equals(olddata.getIsAddReprotError())){
                    QueryWrapper<SwStReportErrorAlterApply> wrappers = new QueryWrapper<>();
                    wrappers.lambda().eq(SwStReportErrorAlterApply::getLineCode,olddata.getLineCode())
                            .eq(SwStReportErrorAlterApply::getStationCode,olddata.getStationCode())
                            .eq(SwStReportErrorAlterApply::getReprotTime,olddata.getStatisticsDate())
                            .ne(SwStReportErrorAlterApply::getCheckStatus,"4")
                            .eq(SwStReportErrorAlterApply::getReportNameId,"12");
                    SwStReportErrorAlterApply swStReportErrorAlterApply = new SwStReportErrorAlterApply();
                    swStReportErrorAlterApply.setIsModify("1");
                    swStReportErrorAlterApply.setModifyTime(new Date());
                    swStReportErrorAlterAppayMapper.update(swStReportErrorAlterApply,wrappers);
                }
                list.add(swStStock);
            }
        } catch (ParseException e){
            e.printStackTrace();
        }
        return R.ok(swStStockService.updateBatchById(list));
    }

    /**
     * 新增
     *
     * @param swStStock
     * @return R
     */
    @ApiOperation(value = "新增", notes = "新增")
    //@SysLog("新增")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swststock_add')")
    public R save(@RequestBody SwStStock swStStock) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String statisticsDate = sdf.format(swStStock.getStatisticsDate());
        String lineCode = SecurityUtils.getUser().getLineCode();
        String stationCode = SecurityUtils.getUser().getStationCode();
        Map req = new HashMap<>();
        req.put("ticket_type_en",swStStock.getTicketTypeEn());
        req.put("ticket_type_param_en",swStStock.getTicketTypeParamEn());
        req.put("statistics_date",statisticsDate);
        req.put("line_code",lineCode);
        req.put("station_code",stationCode);
        Collection collection = swStStockService.listByMap(req);
        if(null != collection && 0 != collection.size()){
            return R.failed(statisticsDate + "数据已存在，不允许新增");
        }
        swStStock.setDelFlag("0");
        return R.ok(swStStockService.save(swStStock));
    }

    /**
     * 修改
     *
     * @param swStStock
     * @return R
     */
    @ApiOperation(value = "修改", notes = "修改")
    //@SysLog("修改")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swststock_edit')")
    public R updateById(@RequestBody SwStStock swStStock) {
        SwStStock oldSwStStock = swStStockService.getById(swStStock.getId());
        if(Objects.equals(oldSwStStock.getReportModifyStatus(),"1")){
            SwStmStationDataEntryLog swStmStationDataEntryLog = new SwStmStationDataEntryLog();
            swStmStationDataEntryLog.setRelationId(oldSwStStock.getId());
            swStmStationDataEntryLog.setLogTableName(StmTableCommon.SW_ST_STOCK);
            swStmStationDataEntryLog.setLogInfo(JSONObject.toJSONString(oldSwStStock));
            swStmStationDataEntryLog.setUpdateJobNo(oldSwStStock.getConfirmPersonJobNo());
            swStmStationDataEntryLog.setUpdateJobName(oldSwStStock.getConformPersonName());
            swStmStationDataEntryLog.setUpdateTime(new Date());
            swStmStationDataEntryLogService.save(swStmStationDataEntryLog);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String statisticsDate = sdf.format(swStStock.getStatisticsDate());
        QueryWrapper<SwStStock> wrapper = new QueryWrapper();
        wrapper.eq("line_code",swStStock.getLineCode());
        wrapper.eq("station_code",swStStock.getStationCode());
        wrapper.eq("ticket_type_en",swStStock.getTicketTypeEn());
        wrapper.eq("ticket_type_param_en",swStStock.getTicketTypeParamEn());
        wrapper.eq("statistics_date",swStStock.getStatisticsDate());
        wrapper.ne("id",swStStock.getId());
        int count = swStStockService.count(wrapper);
        if(count>0){
            return R.failed(statisticsDate + "该车票名称的数据已存在，不允许修改为该车票名称！");
        }
        return R.ok(swStStockService.updateById(swStStock));
    }


    /**
     * 通过id查询库存日报表历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询库存日报表历史记录", notes = "通过id查询库存日报表历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        List<Object> LogInfoList = new ArrayList<>();
        List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                        .eq(SwStmStationDataEntryLog::getRelationId, id)
                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_STOCK));
        //返回json串
        if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
            swStmStationDataEntryLogs.stream().forEach(x -> {
                JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                LogInfoList.add(jsonObject);
            });
        }
        return R.ok(LogInfoList);
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    //@SysLog("通过id删除")
    @DeleteMapping("/{id}")
//    @PreAuthorize("@pms.hasPermission('swststock_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStStockService.removeById(id));
    }

    /**
     * 通过id批量删除
     * @param idList id
     * @return R
     */
    @ApiOperation(value = "通过id批量删除", notes = "通过id批量删除")
    //@SysLog("通过id批量删除")
    @DeleteMapping("/delBatch")
    @Transactional
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        swStStockService.removeByIds(idList);
        return R.ok();
    }


    @SneakyThrows
    @ApiOperation(value = "下载车站车票库存日报表模板", notes = "下载车站车票库存日报表模板")
    @PostMapping("/downTemplate")
    public void downTemplate(HttpServletResponse response) {
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("dailyReportTemplate.xls");
//        DownLoadUtil.downloadUtil(response,inputStream,"dailyReportTemplate.xls");
        down(response);
    }

    public void down(HttpServletResponse response){
        BufferedInputStream br = null;
        OutputStream out = null;
        try {
            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xls");
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/dailyReportTemplate.xls");
            //br =  new BufferedInputStream(this.getClass().getResourceAsStream("/dailyReportTemplate.xls"));
            String filePath = "/opt/subway/dailyReportTemplate.xls";
            File file = new File(filePath);
            br =  new BufferedInputStream(new FileInputStream(file));

            byte[] buf = new byte[1024];
            int len = 0;

            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(out != null) {
                try {
                    out.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

//    @ApiOperation(value = "导出车站车票库存日报表", notes = "导出车站车票库存日报表")
//    @GetMapping("/export")
//    public void export(Page page, SwStStock swStStock, HttpServletResponse response) {
//        List<SwStStock> records = swStStockService.page(page, Wrappers.query(swStStock)).getRecords();
//        try {
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            String fileName = URLEncoder.encode("车站车票库存日报表", "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
//            EasyExcel.write(response.getOutputStream(), SwStStock.class)
//                    .registerConverter(new LocalDateTimeConverter())
//                    .registerConverter(new LocalDateConverter()).sheet("车站车票库存日报表").doWrite(records);
//        } catch (IOException e) {
//            log.error("导出车站车票库存日报表失败");
//        }
//    }

    /**
     * 通知
     *
     * @param list
     * @return R
     */
    @ApiOperation(value = "通知", notes = "通知")
    //@SysLog("通知")
    @PutMapping("/confirm")
    @PreAuthorize("@pms.hasPermission('swststock_confirm')")
    public R confirm(@RequestBody List<SwStStock> list) {
        ArrayList<SwMessageDTO> swMessageDTOS = new ArrayList<>();
        //TODO 待细化 一方面发通知到待办，另一方面可允许车站编辑
        list.stream().forEach(swStStock -> {
            SwMessageDTO swMessageDTO = ObjectUtils.getDefaultObj(SwMessageDTO.class);
            swMessageDTO.setTitle("title");
            swMessageDTO.setContent("content");
            swMessageDTO.setMsgType("0");
            swMessageDTO.setUrl("url");
            swMessageDTO.setSendDeptCode(swStStock.getStationCode());
            swMessageDTOS.add(swMessageDTO);
            swStStock.setConfirmStatus(CONFIRM_STATUS_YES);
        });
        supportService.saveBatchInner(swMessageDTOS, SecurityConstants.FROM_IN);
        return R.ok(swStStockService.updateBatchById(list));
    }


    @ApiOperation(value = "定时任务统计", notes = "每天定时统计前一天票量")
    @Inner
    @PostMapping("/calc")
    public R calc() {
        /*
		String dateTime = DateUtilStm.asPreDateString(LocalDateTime.now());
        List<SwStStockDTO> list = swStStockService.calcData(dateTime);
        List<SwStStock> listDB = new ArrayList<>();
        list.forEach(ticket -> {
            SwStStock db = swStStockService.getOne(Wrappers.<SwStStock>query().lambda()
                    .eq(SwStStock::getStatisticsDate, ticket.getStatisticsDate())
                    .eq(SwStStock::getLineCode, ticket.getLineCode())
                    .eq(SwStStock::getStationCode, ticket.getStationCode())
                    .eq(SwStStock::getTicketTypeEn, ticket.getTicketTypeEn())
                    .eq(SwStStock::getTicketTypeParamEn, ticket.getTicketTypeParamEn()));
            if (null == db) {
                db = new SwStStock();
            }
            BeanUtils.copyProperties(ticket, db);
            db.setDelFlag(CommonConstants.STATUS_NORMAL);
            listDB.add(db);
        });
        if (!listDB.isEmpty()) {
            return R.ok(swStStockService.saveOrUpdateBatch(listDB));
        }*/
        return R.ok();
    }


    /**
     * 生成日报表
     *
     * @param swStStock
     * @return
     */
    @ApiOperation(value = "生成日报表", notes = "生成日报表")
    //@SysLog("生成日报表")
    @PostMapping("/generateReport")
    public R generateReport(@RequestBody SwStStock swStStock) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(swStStock.getStatisticsDate());
        calendar.add(Calendar.DAY_OF_MONTH,-1);
        Date time = calendar.getTime();
        SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
        String statisticsDate = dff.format(time);
        Map req = new HashMap();
        req.put("statistics_date",statisticsDate);
        req.put("line_code",swStStock.getLineCode());
        req.put("station_code",swStStock.getStationCode());
        req.put("DEL_FLAG","0");
        Collection collection = swStStockService.listByMap(req);
        if(null == collection || 0 == collection.size())
            return R.failed(statisticsDate + "数据不存在，不允许生成当前日期数据");
        req.put("statistics_date",dff.format(swStStock.getStatisticsDate()));
        Collection collection2 = swStStockService.listByMap(req);
        if(null != collection2 && 0 != collection2.size())
            return R.failed(dff.format(swStStock.getStatisticsDate()) + "数据已存在，不允许生成当前日期数据");
        PigxUser user = SecurityUtils.getUser();
        swStStock.setCreatorJobNo(user.getUserCode());
        boolean b = swStStockService.generateReport(swStStock, collection);
        if(!b)
            return R.failed("生成失败");
        return R.ok();
    }


    /**
     * 导入车站车票库存日报表
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "导入车站车票库存日报表", notes = "导入车站车票库存日报表")
    //@SysLog("导入车站车票库存日报表")
    @PostMapping("/importExcel")
    public R importExcel(@RequestParam("file") MultipartFile file) throws Exception {
//        try {
//            EasyExcel.read(file.getInputStream(), SwStStock.class,
//                    new UploadDataListener(swStStockService, SwStStock.class)).sheet().doRead();
//            return R.ok("导入成功");
//        } catch (IOException e) {
//            log.info(e.getMessage());
//            return R.ok("导入失败");
//        }
        try {
            PigxUser user = SecurityUtils.getUser();
            List<SwStStock> swStStockList = new ArrayList<>();
            String sqlTicket = "select main_en_name AS mainEnName, main_name AS mainName, sub_en_name AS subEnName, sub_name AS subName " +
                    "from SW_PM_TICKET_CARD_TYPE_PARAM  WHERE DEL_FLAG='0' order by main_en_name,sub_en_name";
            List<Map<String, Object>> mapsTicket = JdbcUtil.exeSqlQuery(sqlTicket);

            final File excelFile = MultipartFileToFile.multipartFileToFile(file);
            List<Map<Integer, String>> listMap = EasyExcel.read(file.getInputStream()).sheet().headRowNumber(1).doReadSync();
            if (CollectionUtil.isNotEmpty(listMap)) {
                MultipartFileToFile.delteTempFile(excelFile);

                for (int m = 0; m < listMap.size(); m++) {
                    Map<Integer, String> data = listMap.get(m);
                    // 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
                    LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
                    SwStStock swStStock = new SwStStock();
                    swStStock.setLineCode(user.getLineCode());
                    swStStock.setStationCode(user.getStationCode());
                    if (data.get(0) == null || data.get(0).isEmpty()) {
                        return R.failed("请检查 第" + (m+2) +"行 日期存在空值！");
                    }
                    String format = "yyyy/MM/dd HH:mm:ss";
                    if(data.get(0).length()<=10){
                        format = "yyyy/MM/dd";
                    }
                    boolean date = DateUtilStm.isDate(data.get(0), format);//检查日期格式是否正确
                    if(!date){
                        return R.failed("请检查 第" + (m+2) +"行 日期格式是否正确！");
                    }
                    swStStock.setStatisticsDate(DateUtilStm.stringToDate(data.get(0),format));
                    if(StringUtils.isEmpty(data.get(1)) || StringUtils.isEmpty(data.get(2))){
                        return R.failed("请检查 第" + (m+2) +"行 票种和车票格式是否正确！");
                    }
                    Map<String, Object> ticketValue = getTicketValue(mapsTicket, data.get(1), data.get(2));
                    if(ObjectUtil.isEmpty(ticketValue)){
                        return R.failed("请检查 第" + (m+2) +"行 票种和车票格式是否正确！");
                    }
                    swStStock.setTicketTypeEn(String.valueOf(ticketValue.get("mainEnName")));//票种
                    swStStock.setTicketTypeParamEn(String.valueOf(ticketValue.get("subEnName")));//车票名称
                    swStStock.setDelFlag("0");
                    List<SwStStock> serviceOne = swStStockService.list(Wrappers.query(swStStock));
                    swStStock.setCreatorId(user.getId());
                    swStStock.setDeptId(user.getDeptId());
                    swStStock.setCreatorName(user.getNikeName());
                    swStStock.setCreateTime(LocalDateTime.now());
					
					boolean isNeedAdd = true;
                    if(ObjectUtil.isNotEmpty(serviceOne)){
                        swStStock.setId(serviceOne.get(0).getId());
						if(Objects.equals(serviceOne.get(0).getConfirmStatus(),"1")){//存在，且已提交状态不更新,其他正常操作
						    isNeedAdd = false;
						}
                    }
                    swStStock.setBalanceLastday(getIntData(data.get(3)));//上日结存
                    swStStock.setTransferStation(getIntData(data.get(4)));//调入本站
                    swStStock.setDistributionStation(getIntData(data.get(5)));//配入本站
                    swStStock.setAgmRecovery(getIntData(data.get(6)));//AGM回收
                    swStStock.setBoxOfficeSale(getIntData(data.get(7)));//票房售出
					swStStock.setTicketReplace(getIntData(data.get(8)));//车票替换  20231227新增
                    swStStock.setTvmSellOut(getIntData(data.get(9)));//TVM售出
                    swStStock.setInternetSales(getIntData(data.get(10)));//网络售出
                    swStStock.setBomScrapTicket(getIntData(data.get(11)));//BOM废票
                    swStStock.setTvmScrapTicket(getIntData(data.get(12)));//TVM废票
                    swStStock.setAgmScrapTicket(getIntData(data.get(13)));//AGm废票
                    swStStock.setNetworkScrapTicket(getIntData(data.get(14)));//网络机废票
                    swStStock.setScrapSubtotal(getIntData(data.get(15)));//废票小计
                    swStStock.setLeaveStation(getIntData(data.get(16)));//调出本站
                    swStStock.setHandTicket(getIntData(data.get(17)));//上交车票
                    swStStock.setArtificialRecovery(getIntData(data.get(18)));//人工回收
                    swStStock.setBalanceToday(getIntData(data.get(19)));//本日结存
					if(data.get(8)!=null && data.get(8)!="0" ){
					  swStStock.setRemark("车票替换"+String.valueOf(data.get(8))+"张");
					}
					
					if(isNeedAdd){
					 swStStockList.add(swStStock);
					}
                   
                }
                if(CollectionUtil.isNotEmpty(swStStockList)){
                        return R.ok(swStStockService.saveOrUpdateBatch(swStStockList));
                }else{
				    return R.failed("导入失败，没有符合要导入的数据,请确认要导入的数据是未提交状态！");
				}
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("导入失败，请检查数据后重新导入！");
        }
        return R.ok();
    }

    private int getIntData(String param){
        if(ObjectUtil.isEmpty(param)){
            return 0;
        }
        if(param.contains(".")){
            String[] split = param.split("\\.");
            Integer integer = Integer.valueOf(split[0]);
            return integer;
        }
        return Integer.valueOf(param);
    }
    private Map<String,Object> getTicketValue( List<Map<String,Object>> listMap,String mainName,String subName) {
        if(listMap == null || listMap.isEmpty()) {
            return null;
        }
        for (Map<String,Object> map : listMap){
            String mainNameInit = String.valueOf(map.get("mainName"));
            String subNameInit = String.valueOf(map.get("subName"));
            if(mainNameInit.equals(mainName) && subNameInit.equals(subName)) {
                return map;
            }
        }
        return null;
    }

    private String getCellContent(Cell cell){
        String cellValue="";
        if(cell == null) {
            return "";
        }else if(cell.getCellTypeEnum().ordinal() == org.apache.poi.ss.usermodel.CellType.NUMERIC.ordinal()) {
            if(HSSFDateUtil.isCellDateFormatted(cell)) {
                SimpleDateFormat sm=new SimpleDateFormat("yyyy-MM-dd");
                Date javaDate = HSSFDateUtil.getJavaDate(Double.valueOf(cell.getNumericCellValue()));
                cellValue = sm.format(javaDate);
            }else{
                double value = cell.getNumericCellValue();
                DecimalFormat decimalFormat = new DecimalFormat("0");
                cellValue = decimalFormat.format(value);
            }
        }else if (cell.getCellTypeEnum().ordinal() == org.apache.poi.ss.usermodel.CellType.STRING.ordinal()){
            cellValue = cell.getStringCellValue();
        }else if (cell.getCellTypeEnum().ordinal() == org.apache.poi.ss.usermodel.CellType.BLANK.ordinal()){
            cellValue = "";
        }else {

            return "";
        }
        return cellValue;
    }
    /**
     * 导出车站车票库存日报表
     * @param statisticsDate
     * @param response
     */
    @GetMapping("/export/{statisticsDate}")
    @ApiOperation(value = "导出车站车票库存日报表", notes = "导出车站车票库存日报表")
    public void export(@PathVariable(value = "statisticsDate") String statisticsDate, HttpServletResponse response) throws SQLException {

        PigxUser user = SecurityUtils.getUser();
        SwStStock swStStock = new SwStStock();
        swStStock.setStatisticsDate(DateUtilStm.stringToDate(statisticsDate));
        swStStock.setLineCode(user.getLineCode());
        swStStock.setStationCode(user.getStationCode());
        swStStock.setDelFlag("0");
        swStStockService.export(swStStock,response);
    }
}
